import 'package:sqflite/sqflite.dart';

class SqliteUtil {
  static final sqliteContext = SqliteUtil();
  final String dbname = 'renqing2.db';

  static SqliteUtil getInstance() {
    return sqliteContext;
  }

  String join(String path) {
    return '$path/$dbname';
  }

  isTableExits(String tableName) async {
    Database db = await openDb(dbname);
    var res = await db.rawQuery(
        "select * from Sqlite_master where type = 'table' and name = '$tableName'");
    return res != null && res.length > 0;
  }

  createDb(int vers) async {
    //获取数据库路径
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath);
    await openDatabase(
      path,
      version: vers,
      onUpgrade: (Database db, int oldVersion, int newVersion) async {},
      onCreate: (Database db, int vers) async {
        await db.execute("CREATE TABLE RenqingList ("
            "id INTEGER PRIMARY KEY,"
            "data TEXT"
            ")");
        await db.close();
      },
    );
  }

  createTable(createText) async {
    Database db = await openDb(dbname);
    await db.execute(createText);
    await db.close();
  }

  _getDbPath(dbname) async {
    //获取数据库路径
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath);
    return path;
  }

  Future<Database> openDb(dbname) async {
    var path = await _getDbPath(dbname);

    Database db = await openDatabase(path);

    return db;
  }

  ///增
  insert(String sql) async {
    var path = await _getDbPath(dbname);

    Database db = await openDatabase(path);
    var rowaffect = await db.transaction<int>((txn) async {
      int count = await txn.rawInsert(sql);
      return count;
    });
    await db.close();
    return rowaffect;
  }

  ///删
  delete(String sql) async {
    var path = await _getDbPath(dbname);
    Database db = await openDatabase(path);
    int count = await db.rawDelete(sql);
    await db.close();
    return count;
  }

  ///改
  update(String sql, List arg) async {
    var path = await _getDbPath(dbname);
    Database db = await openDatabase(path);
    int count = await db.rawUpdate(sql, arg); //修改条件，对应参数值
    await db.close();
    return count;
  }

  ///查条数
  getQueryNum(String sql) async {
    var path = await _getDbPath(dbname);
    Database db = await openDatabase(path);
    int count = Sqflite.firstIntValue(await db.rawQuery(sql));
    await db.close();
    return count;
  }

  ///查全部
  query(String sql) async {
    var path = await _getDbPath(dbname);
    Database db = await openDatabase(path);
    List<Map> list = await db.rawQuery(sql);
    await db.close();
    return list;
  }
}
